package com.eastedu.superise.handler.question.handler.completion;

import com.eastedu.common.model.question.Fragment;
import com.eastedu.common.model.question.QuestionItemContent;
import com.eastedu.superise.handler.question.handler.ContentConverter;
import com.eastedu.superise.handler.question.handler.PatternConstant;

import java.util.ArrayList;
import java.util.List;

/**
 * Answer content converter.
 * P0 [{a　　ｂ},{c　　d　　e},{　　f　　g},{h　　}]       => [{a}], [{b},{c}], [{d}], [{e}], [{f}], [{g},{h}]
 * P1 [{aｂ},{c　　d　　e},{　　f　　g},{h}]             => [{ab},{c}], [{d}], [{e}], [{f}], [{g},{h}]
 * P2 [{aｂ},{c　　d　　e},{　　fg　　},{h　　}]             => [{ab},{c}], [{d}], [{e}], [{fg}],[{h}]
 *
 * @author Administrator
 */
public class AnswerContentConverter implements ContentConverter {

    @Override
    public void convert(List<QuestionItemContent> contents) {
        List<QuestionItemContent> newAnswers = new ArrayList<>();
        for (QuestionItemContent itemContent : contents) {
            //复制段落样式信息,并缓存到段落集合中
            QuestionItemContent questionItemContent = QuestionItemContent.copyWithoutFragment(itemContent);
            newAnswers.add(questionItemContent);

            for (Fragment fragment : itemContent.getFragments()) {
                String fragmentContent = fragment.getContent();
                // 匹配全角空格
                if (fragmentContent.matches(".*\\u3000+.*")) {

                    // 以全角进行分隔
                    String[] split = fragmentContent.split("\\u3000+");
                    newAnswers.get(newAnswers.size() - 1).getFragments().add(createFragmentWithoutOrder(fragment, split[0]));
                    for (int i = 1; i < split.length; i++) {
                        String splitContent = split[i];
                        // 复制段落样式信息
                        QuestionItemContent i0 = QuestionItemContent.copyWithoutFragment(itemContent);

                        // 复制文本样式信息
                        Fragment f = createFragmentWithoutOrder(fragment, splitContent);
                        i0.getFragments().add(f);
                        newAnswers.add(i0);
                    }
                } else {
                    newAnswers.get(newAnswers.size() - 1).getFragments().add(createFragmentWithoutOrder(fragment, fragmentContent));

                }
            }
        }
        contents.clear();
        contents.addAll(newAnswers);
    }

    private Fragment createFragmentWithoutOrder(Fragment fragment, String content) {
        Fragment f = Fragment.copyWithoutContent(fragment, true);
        f.setContent(content.replaceAll(PatternConstant.START_WITH_ORDER, ""));
        return f;
    }

}
